package cn.nfwx.tv.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.os.Looper;
import android.os.MessageQueue;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.widget.Toast;


/**
 * Created by chan on 2017/4/2.
 */
public class ToastUtil {
    private static Toast TOAST;
    private static final String TAG = "ToastUtil";


    //短时间吐司
    public static void show(Context context, int resourceID) {
        show(context, resourceID, Toast.LENGTH_SHORT);
    }

    //短时间吐司
    public static void show(Context context, String text) {
        show(context, text, Toast.LENGTH_SHORT);
    }

    //自定义时长吐司
    public static void show(Context context, Integer resourceID, int duration) {
        if (context == null || context.getResources() == null) {
            return;
        }
        String text = context.getResources().getString(resourceID);// 用于显示的文字
        show(context, text, duration);
    }

    //自定义时长吐司
    @SuppressLint("ShowToast")
    public static void show(@NonNull final Context context, @NonNull final String text, final int duration) {
        if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
            if (TOAST == null) {
                TOAST = Toast.makeText(context.getApplicationContext(), text, duration);
            } else {
                TOAST.setText(text);
                TOAST.setDuration(duration);
            }
            //TOAST.setGravity(Gravity.BOTTOM, 0, 0);
            TOAST.show();
        }else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                Looper.getMainLooper().getQueue().addIdleHandler(new MessageQueue.IdleHandler() {
                    @Override
                    public boolean queueIdle() {
                        if (TOAST == null) {
                            TOAST = Toast.makeText(context.getApplicationContext(), text, duration);
                        } else {
                            TOAST.setText(text);
                            TOAST.setDuration(duration);
                        }
                        TOAST.show();
                        return false;
                    }
                });
            }
        }
    }
}
